#!/usr/bin/python3

from PIL import Image

P = [(84, 84, 84), (0, 30, 116), (8, 16, 144), (48, 0, 136), (68, 0, 100), (92, 0, 48), (84, 4, 0), (60, 24, 0), 
               (32, 42, 0), (8, 58, 0), (0, 64, 0), (0, 60, 0), (0, 50, 60), (0, 0, 0), (0, 0, 0), (0, 0, 0), 
               (152, 150, 152), (8, 76, 196), (48, 50, 236), (92, 30, 228), (136, 20, 176), (160, 20, 100), (152, 34, 32), (120, 60, 0), 
               (84, 90, 0), (40, 114, 0), (8, 124, 0), (0, 118, 40), (0, 102, 120), (0, 0, 0), (0, 0, 0), (0, 0, 0), 
               (236, 238, 236), (76, 154, 236), (120, 124, 236), (176, 98, 236), (228, 84, 236), (236, 88, 180), (236, 106, 100), (212, 136, 32), 
               (160, 170, 0), (116, 196, 0), (76, 208, 32), (56, 204, 108), (56, 180, 204), (60, 60, 60), (0,0,0), (0,0,0),
               (236, 238, 236), (168, 204, 236), (188, 188, 236), (212, 178, 236), (236, 174, 236), (236, 174, 212), (236, 180, 176), (228, 196, 144), 
               (204, 210, 120), (180, 222, 120), (168, 226, 144), (152, 226, 180), (160, 214, 228), (160, 162, 160), (0,0,0), (0,0,0)]

def rgb2nes(r, g, b):
    dist = 256*256*3 + 1
    q = -1
    for i in range(64):
        (R,G,B)=P[i]
        d = (R-r)*(R-r) + (G-g)*(G-g) + (B-b)*(B-b)
        if d < dist:
            dist = d
            q = i
    return q

def image2nes(img):
    nes = [[0 for i in range(256)] for i in range(240)]
    for y in range(240):
        for x in range(256):
            p=img.getpixel((x, y))
            nes[y][x] = rgb2nes(p[0], p[1], p[2])
    return nes

# with Image.open('nestang.png') as im:
#     if im.size != (256, 240):
#         print('Please resize to 256*240')
#         exit(1)
#     for x in range(256):
#         for y in range(240):
#             p = im.getpixel((x, y))
#             q = rgb2nes(p[0], p[1], p[2])
#             # if q != 13:
#             #     print('{},{}={}'.format(x, y, q))
#             im.putpixel((x,y), P[q])
#     im.save('res.png')